package com.example.zn.controller;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.zn.dto.ProductDetails;
import com.example.zn.dto.Result;
import com.example.zn.entity.Admin;
import com.example.zn.entity.Category;
import com.example.zn.entity.Product;
import com.example.zn.service.CategoryService;

import com.example.zn.service.ProductService;
import com.example.zn.service.impl.ProductServiceImpl;
import com.example.zn.utils.QiniuOssUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Tag(name = "商品管理",description = "商品的上传，列表，更新，删除下架等操作")
@CrossOrigin
@RestController


public class ProductController {


    @Autowired
    private ProductServiceImpl productService;
    @Autowired
    private CategoryService categoryService;

    @Operation(summary = "根据id修改商品",description = "需要提供商品的id")
    @PostMapping("/product/update")
    public Result modify(@Parameter(description = "商品对象") @RequestBody Product product){
        if (productService.updateById(product)){
            return Result.ok().setMsg("修改成功").setData(product);

        }
        return Result.fail().setMsg("修改失败");
    }


    /**
     * 根据id删除商品员(物理删除：谨慎操作)
     *
     * @param id
     * @return
     */
    @Operation(summary = "根据id删除商品",description = "需要提供商品的id")
    @DeleteMapping("/product/{id}")
    public Result delById(@Parameter(description = "商品id", required = true) @PathVariable("id") Integer id){
        Product product = productService.getById(id);
        if (Objects.isNull(product)){
            return Result.fail().setMsg("该商品不存在！");
        }
        if (productService.removeById(id)){
            return Result.ok().setMsg("删除成功").setData(product);
        }
        return Result.fail().setMsg("删除失败");
    }

    @Operation(summary = "商品图片上传")
    @Parameters({
            @Parameter(name = "product",description = "商品"),
            @Parameter(name = "myfile",description = "上传的商品图片")
    })
    @PostMapping("/product/upload")
    public Result upload(Product product, MultipartFile myfile) throws IOException {
//        文件名
        String fname = myfile.getOriginalFilename();
//        文件大小
        long size = myfile.getSize();
        //上传到服务端的文件流（字节输入流）
        InputStream is = myfile.getInputStream();
        //创建key(文件的唯一标识)
        String key = UUID.randomUUID().toString();
        //创建七牛工具
        QiniuOssUtils utils = new QiniuOssUtils();
        //执行上传并且获取返回的文件地址
        String path = utils.upload(is, key);

        product.setImg(path);

        //执行持久化操作
        if(productService.save(product)){
            return Result.ok().setMsg("上传成功").setData(product);
        }
        //删除已上传的文件
        utils.delete(key);
        return Result.fail().setMsg("上传失败");
    }

    //    分页查询
    @Operation(summary = "分页查询商品",description = "显示所有商品信息")
    @Parameters({  //参数集
            @Parameter(name = "page", description = "当前页"),
            @Parameter(name = "limit", description = "每页数据条目数")
    })
    @GetMapping("/product/list")
    public Result list( @RequestParam(defaultValue = "1")Integer page, @RequestParam(defaultValue = "5")Integer limit){
//        log.info("page={},limit={}",page,limit);
//        执行分页查询
        List<Product> list = productService.list(new Page<Product>(page, limit));
        List<ProductDetails> details = listConvertor(list);
        long count = productService.count();
        return Result.ok().setMsg("查询成功").setData(details).setCount((int)count);
    }

    @Operation(summary = "根据商品名称查询",description = "模糊查询，提供关键字即可实现")
    @GetMapping("/product/query")
    public Result query(@Parameter(description = "商品关键字") String key){
        // where name like '%key%'
        QueryWrapper<Product> query = Wrappers.query(Product.class);
        query.like("name",key);
        //执行模糊查询
        List<Product> list = productService.list(query);
        //根据条件查询符合条件的总数
        long count = productService.count(query);
        //List<Product>  =>  List<ProductDetails>
        List<ProductDetails> details = listConvertor(list);
        return Result.ok().setMsg("查询完成").setData(details).setCount((int)count);
    }

    /**
     * 集合转换工具，将List<Product>集合转换为List<ProductDetails>集合
     * @param list
     * @return
     */
    private List<ProductDetails> listConvertor(List<Product> list){
        List<ProductDetails> details = new ArrayList<>();

//        循环遍历商品集合，利用子查询查询商品分类表
        list.forEach(product -> {
            Integer categoryid = product.getCategoryid();

            Category category = categoryService.getById(categoryid);

//            创建商品详情对象
            ProductDetails md = new ProductDetails();
            //转移商品信息到详情对象
            md.setProid(product.getProid());
            md.setName(product.getName());
            md.setPrice(product.getPrice());
            md.setProcount(product.getProcount());
            md.setImg(product.getImg());
            md.setShelfTime(product.getShelftime());


//            商品分类
            md.setCategoryId(category.getId());
            md.setCategoryName(category.getName());

            details.add(md);
        });

        return details;


    


}
}
